import React,{useEffect,useState} from 'react'
import  {useDispatch,useSelector} from  "react-redux"
import  {initList,delListById,addListItem} from  "../reducers/userReducer"
import { userModel } from '../model/userMode';

export default function User2() {

    let dispatch = useDispatch();
    let list = useSelector((state:any)=>state.userInfo.list);

    let [username,setUsername] = useState("");
    let [userpwd,setUserpwd] = useState("");
   
    useEffect(() => {
        userModel.query({}).then((res)=>{//res.data
            dispatch(initList(res.data));
            console.log(list);
        })
    }, [])
    
    let  del =async function(id:any){
        await  userModel.del(id);
        dispatch(delListById(id));
    }
    let  add = async function(){
       let {data}= await  userModel.add({username,userpwd});
       dispatch(addListItem(data));
        
    }

  return (
    <div>User2
        <div>
            用户名 <input type="text" value={username} onChange={(e)=>{
                setUsername(e.target.value)

            }} />
        </div>
        <div>
            密码 <input type="text" value={userpwd} onChange={(e)=>{
                setUserpwd(e.target.value)

            }} />
        </div>
        <button onClick={()=>{
            add();
        }}>新增</button>



        <div className='table'>
            <div className='tr'>
                <div className="td">编号</div>
                <div className="td">用户名</div>
                <div className="td">密码</div>
                <div className="td">操作</div>
            </div>
            {list.map((item:any)=>{
                return  ( <div className='tr' key={item.id}>
                <div className="td">{item.id}</div>
                <div className="td">{item.username}</div>
                <div className="td">{item.userpwd}</div>
                <div className="td" onClick={()=>{
                    del(item.id)
                }}>删除</div>
            </div>)
            })}
        </div>
    </div>
  )
}
